"use client"

import { useState } from "react"
import { motion } from "framer-motion"
import { Users, Mic, MicOff, Volume2, Settings, Crown, Star, Zap, AlertTriangle, Lightbulb } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { useToast } from "@/hooks/use-toast"
import { ProtectedRoute } from "@/components/protected-route"
import { useAuth } from "@/contexts/auth-context"

const mockTeams = [
  {
    id: 1,
    name: "AI 冲刺小队",
    competition: "Kaggle - House Prices",
    members: [
      { id: 1, name: "Alex", avatar: "/placeholder.svg?height=40&width=40", skills: ["Python", "ML"], isLeader: true },
      { id: 2, name: "Sarah", avatar: "/placeholder.svg?height=40&width=40", skills: ["R", "Stats"], isLeader: false },
      null,
      null,
    ],
    maxMembers: 4,
    requiredSkills: ["Machine Learning", "Python", "Statistics"],
    difficulty: "Intermediate",
  },
  {
    id: 2,
    name: "Web3 创新团队",
    competition: "Devpost - Climate Hackathon",
    members: [
      {
        id: 3,
        name: "Mike",
        avatar: "/placeholder.svg?height=40&width=40",
        skills: ["Solidity", "React"],
        isLeader: true,
      },
      null,
      null,
      null,
      null,
    ],
    maxMembers: 5,
    requiredSkills: ["Blockchain", "Frontend", "Smart Contracts"],
    difficulty: "Advanced",
  },
]

const mockUsers = [
  { id: 7, name: "David Chen", avatar: "/placeholder.svg?height=40&width=40", skills: ["React", "Node.js", "Python"] },
  { id: 8, name: "Anna Kim", avatar: "/placeholder.svg?height=40&width=40", skills: ["UI/UX", "Figma", "Frontend"] },
  { id: 9, name: "James Wilson", avatar: "/placeholder.svg?height=40&width=40", skills: ["Java", "Spring", "AWS"] },
  { id: 10, name: "Sophie Liu", avatar: "/placeholder.svg?height=40&width=40", skills: ["Spark", "Kafka", "Python"] },
]

// 缺少的技能方向
const missingSkills = [
  { skill: "区块链开发", urgency: "high", teams: 3 },
  { skill: "UI/UX设计", urgency: "medium", teams: 5 },
  { skill: "数据科学", urgency: "high", teams: 2 },
  { skill: "移动开发", urgency: "low", teams: 1 },
  { skill: "DevOps", urgency: "medium", teams: 4 },
]

// 现有创意想法
const existingIdeas = [
  {
    id: 1,
    title: "AI驱动的气候预测平台",
    description: "使用机器学习预测极端天气事件",
    category: "AI/Climate",
    likes: 23,
    author: "Climate Tech Team",
    tags: ["AI", "Climate", "Prediction"],
  },
  {
    id: 2,
    title: "去中心化碳交易市场",
    description: "基于区块链的碳信用交易平台",
    category: "Blockchain/Sustainability",
    likes: 18,
    author: "Green Chain",
    tags: ["Blockchain", "Carbon", "Trading"],
  },
  {
    id: 3,
    title: "智能健康监测手环",
    description: "实时监测用户健康数据并提供建议",
    category: "IoT/Healthcare",
    likes: 31,
    author: "Health Innovators",
    tags: ["IoT", "Health", "Wearable"],
  },
  {
    id: 4,
    title: "AR教育游戏平台",
    description: "沉浸式AR技术让学习更有趣",
    category: "AR/Education",
    likes: 27,
    author: "EduTech Pioneers",
    tags: ["AR", "Education", "Gaming"],
  },
]

export default function LobbyPage() {
  const [teams, setTeams] = useState(mockTeams)
  const [isMicOn, setIsMicOn] = useState(false)
  const [isVoiceOn, setIsVoiceOn] = useState(true)
  const { toast } = useToast()
  const { isAuthenticated } = useAuth()

  const handleJoinTeam = async (teamId: number, slotIndex: number) => {
    if (!isAuthenticated) {
      toast({
        title: "⚠️ 需要登录",
        description: "请先登录后再加入团队",
        variant: "destructive"
      })
      return
    }

    toast({
      title: "🔍 正在匹配...",
      description: "为你寻找最佳队友",
    })

    await new Promise((resolve) => setTimeout(resolve, 1500))

    const randomUser = mockUsers[Math.floor(Math.random() * mockUsers.length)]

    setTeams((prevTeams) =>
      prevTeams.map((team) => {
        if (team.id === teamId) {
          const newMembers = [...team.members]
          newMembers[slotIndex] = randomUser
          return { ...team, members: newMembers }
        }
        return team
      }),
    )

    toast({
      title: "🎉 匹配成功！",
      description: `已为你匹配到 ${randomUser.name}，开始组队吧！`,
    })
  }

  const getDifficultyColor = (difficulty: string) => {
    switch (difficulty.toLowerCase()) {
      case "beginner":
        return "bg-green-500/20 text-green-400"
      case "intermediate":
        return "bg-yellow-500/20 text-yellow-400"
      case "advanced":
        return "bg-red-500/20 text-red-400"
      default:
        return "bg-gray-500/20 text-gray-400"
    }
  }

  const getUrgencyColor = (urgency: string) => {
    switch (urgency) {
      case "high":
        return "bg-red-500/20 text-red-400 border-red-500/30"
      case "medium":
        return "bg-yellow-500/20 text-yellow-400 border-yellow-500/30"
      case "low":
        return "bg-green-500/20 text-green-400 border-green-500/30"
      default:
        return "bg-gray-500/20 text-gray-400 border-gray-500/30"
    }
  }

  const handleCreateTeam = () => {
    if (!isAuthenticated) {
      toast({
        title: "⚠️ 需要登录",
        description: "请先登录后再创建团队",
        variant: "destructive"
      })
      return
    }
    // TODO: 实现创建团队逻辑
  }

  const handleFollowTeam = () => {
    if (!isAuthenticated) {
      toast({
        title: "⚠️ 需要登录",
        description: "请先登录后再关注团队",
        variant: "destructive"
      })
      return
    }
    // TODO: 实现关注团队逻辑
  }

  return (
    <ProtectedRoute customMessage="开黑大厅需要登录后才能使用，快来加入我们吧！">
      <div className="min-h-screen pt-20">
        <div className="container mx-auto px-4 py-8">
        {/* 头部 */}
        <motion.div initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} className="text-center mb-12">
          <h1 className="text-5xl font-bold mb-4 bg-gradient-to-r from-purple-400 via-pink-400 to-blue-400 bg-clip-text text-transparent">
            开黑大厅
          </h1>
          <p className="text-xl mb-6" style={{ color: "white" }}>
            找到你的最强队友，一起征服竞赛宇宙
          </p>

          {/* 语音控制 */}
          <div className="flex items-center justify-center gap-4 mb-8">
            <Button
              variant={isMicOn ? "default" : "outline"}
              size="sm"
              onClick={() => setIsMicOn(!isMicOn)}
              className="gap-2"
              style={{ color: "white" }}
            >
              {isMicOn ? <Mic className="w-4 h-4" /> : <MicOff className="w-4 h-4" />}
              {isMicOn ? "麦克风开启" : "麦克风关闭"}
            </Button>
            <Button
              variant={isVoiceOn ? "default" : "outline"}
              size="sm"
              onClick={() => setIsVoiceOn(!isVoiceOn)}
              className="gap-2"
              style={{ color: "white" }}
            >
              <Volume2 className="w-4 h-4" />
              {isVoiceOn ? "语音开启" : "语音关闭"}
            </Button>
            <Button variant="outline" size="sm" className="gap-2 bg-transparent" style={{ color: "white" }}>
              <Settings className="w-4 h-4" />
              设置
            </Button>
          </div>
        </motion.div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          {/* 主要内容 */}
          <div className="lg:col-span-3">
            {/* 队伍列表 */}
            <div className="space-y-8 mb-8">
              {teams.map((team, teamIndex) => (
                <motion.div
                  key={team.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: teamIndex * 0.1 }}
                >
                  <Card className="glass border-0 overflow-hidden">
                    <CardHeader>
                      <div className="flex items-center justify-between">
                        <div>
                          <CardTitle className="flex items-center gap-2" style={{ color: "white" }}>
                            <Crown className="w-5 h-5 text-yellow-400" />
                            {team.name}
                          </CardTitle>
                          <p className="mt-1" style={{ color: "#d1d5db" }}>
                            {team.competition}
                          </p>
                        </div>
                        <div className="flex items-center gap-2">
                          <Badge className={getDifficultyColor(team.difficulty)}>{team.difficulty}</Badge>
                          <Badge variant="outline" style={{ color: "white" }}>
                            {team.members.filter((m) => m !== null).length}/{team.maxMembers}
                          </Badge>
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent>
                      {/* 队员位置 */}
                      <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4 mb-6">
                        {team.members.map((member, index) => (
                          <motion.div key={index} whileHover={{ scale: 1.05 }} className="relative">
                            {member ? (
                              <div className="glass rounded-lg p-4 text-center">
                                <Avatar className="w-12 h-12 mx-auto mb-2">
                                  <AvatarImage src={member.avatar || "/placeholder.svg"} />
                                  <AvatarFallback>{member.name[0]}</AvatarFallback>
                                </Avatar>
                                <h4 className="font-medium text-sm mb-1" style={{ color: "white" }}>
                                  {member.name}
                                </h4>
                                <div className="flex flex-wrap gap-1 justify-center">
                                  {member.skills.slice(0, 2).map((skill) => (
                                    <Badge key={skill} variant="outline" className="text-xs" style={{ color: "white" }}>
                                      {skill}
                                    </Badge>
                                  ))}
                                </div>
                                {member.isLeader && (
                                  <Crown className="absolute -top-1 -right-1 w-4 h-4 text-yellow-400" />
                                )}
                              </div>
                            ) : (
                              <motion.button
                                whileHover={{ scale: 1.05 }}
                                whileTap={{ scale: 0.95 }}
                                onClick={() => handleJoinTeam(team.id, index)}
                                className="glass rounded-lg p-4 text-center border-2 border-dashed border-gray-600 hover:border-purple-400 transition-colors group"
                              >
                                <div className="w-12 h-12 mx-auto mb-2 rounded-full bg-gray-700 flex items-center justify-center group-hover:bg-purple-500/20">
                                  <Users className="w-6 h-6 text-gray-400 group-hover:text-purple-400" />
                                </div>
                                <p className="text-sm text-gray-400 group-hover:text-purple-400">点击加入</p>
                              </motion.button>
                            )}
                          </motion.div>
                        ))}
                      </div>

                      {/* 需要技能 */}
                      <div className="mb-4">
                        <h4 className="text-sm font-medium mb-2" style={{ color: "#d1d5db" }}>
                          需要技能:
                        </h4>
                        <div className="flex flex-wrap gap-2">
                          {team.requiredSkills.map((skill) => (
                            <Badge key={skill} variant="outline" className="gap-1" style={{ color: "white" }}>
                              <Zap className="w-3 h-3" />
                              {skill}
                            </Badge>
                          ))}
                        </div>
                      </div>

                      {/* 操作按钮 */}
                      <div className="flex gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          className="flex-1 bg-transparent"
                          style={{ color: "white" }}
                        >
                          查看详情
                        </Button>
                        <Button
                          size="sm"
                          onClick={handleFollowTeam}
                          className="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600"
                          style={{ color: "white" }}
                        >
                          <Star className="w-4 h-4 mr-1" />
                          关注
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                </motion.div>
              ))}
            </div>

            {/* 创建队伍按钮 */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.5 }}
              className="text-center"
            >
              <Button
                size="lg"
                onClick={handleCreateTeam}
                className="bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600 gap-2"
                style={{ color: "white" }}
              >
                <Users className="w-5 h-5" />
                创建我的队伍
              </Button>
            </motion.div>
          </div>

          {/* 侧边栏 */}
          <div className="lg:col-span-1">
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.3 }}
              className="space-y-6"
            >
              {/* 缺少的技能方向 */}
              <Card className="glass border-0 card-hover">
                <CardHeader>
                  <CardTitle className="text-lg flex items-center gap-2" style={{ color: "white" }}>
                    <AlertTriangle className="w-5 h-5 text-red-400" />
                    急需技能
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  {missingSkills.map((item, index) => (
                    <motion.div
                      key={item.skill}
                      initial={{ opacity: 0, x: 20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: 0.5 + index * 0.1 }}
                      className={`p-3 rounded-lg border team-need ${getUrgencyColor(item.urgency)}`}
                    >
                      <div className="flex items-center justify-between mb-1">
                        <span className="font-medium text-sm">{item.skill}</span>
                        <Badge variant="outline" className="text-xs">
                          {item.teams} 队伍需要
                        </Badge>
                      </div>
                      <div className="text-xs opacity-80">
                        紧急程度: {item.urgency === "high" ? "高" : item.urgency === "medium" ? "中" : "低"}
                      </div>
                    </motion.div>
                  ))}
                </CardContent>
              </Card>

              {/* 现有创意想法 */}
              <Card className="glass border-0 card-hover">
                <CardHeader>
                  <CardTitle className="text-lg flex items-center gap-2" style={{ color: "white" }}>
                    <Lightbulb className="w-5 h-5 text-yellow-400" />
                    创意想法池
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  {existingIdeas.map((idea, index) => (
                    <motion.div
                      key={idea.id}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: 0.7 + index * 0.1 }}
                      className="p-3 rounded-lg team-idea cursor-pointer hover:bg-green-500/30 transition-colors"
                    >
                      <h4 className="font-medium text-sm mb-1">{idea.title}</h4>
                      <p className="text-xs mb-2 opacity-80">{idea.description}</p>
                      <div className="flex items-center justify-between">
                        <div className="flex flex-wrap gap-1">
                          {idea.tags.slice(0, 2).map((tag) => (
                            <Badge key={tag} variant="outline" className="text-xs">
                              {tag}
                            </Badge>
                          ))}
                        </div>
                        <div className="flex items-center gap-1 text-xs">
                          <Star className="w-3 h-3" />
                          {idea.likes}
                        </div>
                      </div>
                      <div className="text-xs mt-1 opacity-60">by {idea.author}</div>
                    </motion.div>
                  ))}
                </CardContent>
              </Card>

              {/* 大厅统计 */}
              <Card className="glass border-0 card-hover">
                <CardHeader>
                  <CardTitle className="text-lg flex items-center gap-2" style={{ color: "white" }}>
                    <Users className="w-5 h-5 text-blue-400" />
                    大厅统计
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="text-center">
                    <div className="text-2xl font-bold text-blue-400 mb-1">24</div>
                    <div className="text-sm" style={{ color: "#d1d5db" }}>
                      活跃队伍
                    </div>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-green-400 mb-1">156</div>
                    <div className="text-sm" style={{ color: "#d1d5db" }}>
                      在线用户
                    </div>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-purple-400 mb-1">89</div>
                    <div className="text-sm" style={{ color: "#d1d5db" }}>
                      今日匹配
                    </div>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </div>
          </div>
        </div>
      </div>
    </ProtectedRoute>
  )
}
